/*
 * 文件名： ScanPaySpdbServiceImpl.java
 * 
 * 工程名称: bis-service
 *
 * Gopay
 *
 * 创建日期： 2017年11月9日
 *
 * Copyright(C) 2017, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.service.bank.impl.scan;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.manager.bank.micro.SpdbMicroPayManager;
import com.gopay.bis.manager.bank.scan.ScanPaySpdbManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.SpdbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.spdb.agpay.PayNotify;
import com.gopay.common.domain.bank.spdb.agpay.QueryOrderBody;
import com.gopay.common.domain.bank.spdb.agpay.RefundBody;
import com.gopay.common.domain.bank.spdb.agpay.ScanPayBody;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayResultMsg;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayServerNotifyMsg;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.ScanPayInteractRemoteService;

/**
 * 聚合支付浦发银行渠道
 *
 * @author 宣广海
 *
 * @version 
 *
 * @since 2017年11月9日
 */
public class ScanPaySpdbServiceImpl implements ScanPayInteractRemoteService{
	
	@Resource(name = "scanPaySpdbManager")
	private ScanPaySpdbManager manager;
	
	@Resource(name = "mpPaySpdbManager")
	private SpdbMicroPayManager mpPaySpdbManager;
	/**
	 * 日志对象
	 */
	private static Logger logger = LoggerFactory.getLogger(ScanPaySpdbServiceImpl.class);
	@Override
	public Result pay(BaseMessage msg) throws GopayException {

		logger.info("------------ScanPaySpdbServiceImpl pay start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result(false);
		try {
			ScanPayBody resMessage = (ScanPayBody) manager
					.payment(msg);
			logger.info("---扫码支付浦发渠道返回处理对象：" + ToStringBuilder.reflectionToString(resMessage));
			/**
			 * 定义扫码返回对象
			 */
			ScanPayResultMsg respMsg = new ScanPayResultMsg();
			if (resMessage.getRespcd().equals("09")&&StringUtils.isNotBlank(resMessage.getQrcode())) {
				BeanUtils.copyProperties(resMessage, respMsg);

				respMsg.setCodeUrl(resMessage.getQrcode());
				respMsg.setCodeImage(resMessage.getQrcode());

				respMsg.setCode_url(resMessage.getQrcode());
				respMsg.setCode_img_url(resMessage.getQrcode());

				result.setDefaultModel(respMsg); // 收银台从ScanPayBaseMessage类获取支付请求结果
				result.setSuccess(true);
			} else {
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E1161);
				result.setErrorMsg(resMessage.getErrorDetail());
				result.setSuccess(false);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E1161);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ ScanPaySpdbServiceImpl pay end，耗时(ms):" + (endTime - beginTime));
		return result;	
	}

	@Override
	public Result orderQuery(BaseMessage msg) throws GopayException {
		logger.info("------------ScanPaySpdbServiceImpl orderQuery start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result();
		try {
			QueryOrderBody resMsg = (QueryOrderBody) mpPaySpdbManager
					.orderQuery(msg);
			logger.info("---扫码支付浦发渠道订单查询返回处理对象：" + ToStringBuilder.reflectionToString(resMsg));			
			resMsg.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(String.valueOf(new BigDecimal(resMsg.getTxamt())))));
			result.setDefaultModel(resMsg);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ ScanPaySpdbServiceImpl orderQuery end，耗时(ms):" + (endTime - beginTime));
		return result;
	
	}

	@Override
	public Result refund(BaseMessage msg) throws GopayException {

		logger.info("------------ScanPaySpdbServiceImpl refund start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result(false);
		try {
			RefundBody resMsg = (RefundBody) mpPaySpdbManager
					.refund(msg);
			if (resMsg != null) {
				if (SpdbConstants.RESPCODE_SUCCESS.equals(resMsg.getRespcd())){
					result.setDefaultModel(resMsg);
					result.setSuccess(true);
					// 接收成功
					result.setModel("falg", true);
				} else {
					result.setSuccess(false);
					result.setModel("falg", false);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
					result.setErrorMsg(resMsg.getErrorDetail());
				}
			} else {
				result.setSuccess(false);
				result.setModel("falg", false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ ScanPaySpdbServiceImpl refund end，耗时(ms):" + (endTime - beginTime));
		return result;
	
	}

	@Override
	public Result refundQuery(BaseMessage msg) throws GopayException {

		logger.info("------------ScanPaySpdbServiceImpl refundQuery start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result();
		try {
			QueryOrderBody resMsg = (QueryOrderBody) mpPaySpdbManager
					.orderQuery(msg);
			logger.info("---聚合支付扫码浦发银行退款订单查询返回处理对象：" + ToStringBuilder.reflectionToString(resMsg));
			resMsg.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(String.valueOf(new BigDecimal(resMsg.getTxamt())))));
			result.setDefaultModel(resMsg);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ ScanPaySpdbServiceImpl orderQuery end，耗时(ms):" + (endTime - beginTime));
		return result;
	
	}

	@Override
	public Result verify(BaseMessage msg) throws GopayException {
		Result result = new Result(false);
		try {
//			PayNotify verifyMsg = new PayNotify();
//			ScanPayServerNotifyMsg message = (ScanPayServerNotifyMsg) msg;
//			BeanUtils.copyProperties(msg, verifyMsg);
			PayNotify verifyMsg = (PayNotify) msg;
			Boolean flag = (Boolean) mpPaySpdbManager.verify(verifyMsg);
			result.setDefaultModel(flag);
			result.setSuccess(true);
			result.setModel("res", verifyMsg);
			Map<String, String> param = new HashMap<String, String>();
			/**
			 * 验签成功
			 */
			if ((boolean) result.getDefaultModel()) {
					param.put("orderId", verifyMsg.getOrderId());
					param.put("amt", TransUtil.amountConvert2Yuan(String.valueOf(new BigDecimal(verifyMsg.getTxamt()))));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", "");
					param.put("isFront", String.valueOf(verifyMsg.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					param.put("orderId", verifyMsg.getOrderId());
					param.put("amt", String.valueOf(verifyMsg.getAmount()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "验签失败");
					param.put("signData", "");
					param.put("isFront", String.valueOf(verifyMsg.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	
	}
}
